#include "GroupChat.h"
#include "main.h"

void *chat_thread(void *arg)
{
    // ClientData *client = (ClientData *)arg;

    // char buf[1024];
    // int client_fd = client->socket_fd;
    // int *Acce_fds_array = client->Ac_fds_array;

    // while (1)
    // {
    //     // 清空buf
    //     memset(buf, 0, sizeof(buf));
    //     int ret = recv(client_fd, buf, sizeof(buf), 0);
    //     if (ret <= 0)
    //     {
    //         printf("客户断开连接\n");
    //         close(client_fd);
    //         free(client);
    //         pthread_exit(NULL);
    //     }
    //     // 发送给其他客户端
    //     for (int i = 0; i < MAX_CLIENT; i++)
    //     {
    //         if (Acce_fds_array[i] != client_fd && Acce_fds_array[i] > 0)
    //         {
    //             send(Acce_fds_array[i], buf, ret, 0);
    //             printf("发送给客户端%d的信息:%s\n",Acce_fds_array[i], buf);
    //         }
    //     }
    // }

    ClientData *client_data = (ClientData *)arg;
    int client_fd = client_data->socket_fd;
    sqlite3 *db = client_data->db;
    char buffer[1024];

    while (1) {
        int bytes_read = read(client_fd, buffer, sizeof(buffer));
        if (bytes_read <= 0) {
            // 客户端断开连接，从数组中移除该客户端
            pthread_mutex_lock(&client_array_mutex);
            for (int i = 0; i < MAX_CLIENT; i++) {
                if (clients[i].socket_fd == client_fd) {
                    clients[i].socket_fd = -1;
                    clients[i].db = NULL;
                    break;
                }
            }
            pthread_mutex_unlock(&client_array_mutex);
            printf("Client disconnected\n");
            close(client_fd);
            free(client_data);
            pthread_exit(NULL);
        } else {
            buffer[bytes_read] = '\0';
            if (strncmp(buffer, "SEND_FILE", 9) == 0) {
                char file_path[256];
                sscanf(buffer, "SEND_FILE %s", file_path);
                send_file(client_fd, file_path);
            } else if (strncmp(buffer, "RECEIVE_FILE", 12) == 0) {
                char save_path[256];
                sscanf(buffer, "RECEIVE_FILE %s", save_path);
                receive_file(client_fd, save_path);
            } else {
                // 将消息广播给其他客户端
                pthread_mutex_lock(&client_array_mutex);
                for (int i = 0; i < MAX_CLIENT; i++) {
                    if (clients[i].socket_fd > 0 && clients[i].socket_fd!= client_fd) {
                        send(clients[i].socket_fd, buffer, bytes_read, 0);
                    }
                }
                pthread_mutex_unlock(&client_array_mutex);
                // 打印消息
                printf("Message from client %d: %s\n", client_fd, buffer);
            }
        }
    }

    return NULL;
}